package com.jacobson.huobi.utils

import android.R.attr.publicKey
import android.annotation.TargetApi
import android.os.Build
import androidx.annotation.RequiresApi
import com.jacobson.core.widget.logger.LoggerFactory
import com.jacobson.huobi.R
import java.nio.charset.Charset
import java.security.KeyFactory
import java.security.NoSuchAlgorithmException
import java.security.PublicKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.InvalidKeySpecException
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.RSAPublicKeySpec
import java.security.spec.X509EncodedKeySpec
import java.util.*
import javax.crypto.Cipher


class RSAUtil {

    private val logger = LoggerFactory.getLogger()

    private  val ALGORITHM_RSA = "RSA"
    private val UTF_8 = Charsets.UTF_8

    /**
     * 用公钥对字符串进行加密
     *
     * @param data 原文
     */

    @TargetApi(Build.VERSION_CODES.O)
    fun encryptByPublicKey(
        data: String
    ): String {
        try {
//            var keyData =  RSAGenerator.decode(ResourcesUtil.formatString(R.string.rsa_public_key))
//            val keyData = RSAGenerator().decode() (Base64Util.DecoderStr(ResourcesUtil.formatString(R.string.rsa_public_key)).toByte())
//            val keyData1 = Base64.getDecoder().decode(ResourcesUtil.formatString(R.string.rsa_public_key))
            // 默认编码
//            val keyFactory = KeyFactory.getInstance(ALGORITHM_RSA)
//            val pkcs8eks = X509EncodedKeySpec(keyData)
//            val keyPublic = keyFactory.generatePublic(pkcs8eks) as RSAPublicKey

            // 加密数据
            var result = RSAGenerator().encryptByPublic(data, ResourcesUtil.formatString(R.string.rsa_public_key))

            return result
        }catch (e:Exception) {
            logger.e("明文:"+ data +"加密失败" + e)
            return ""
        }
    }

}